package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.db.datasource.DataSourceUtil;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.SysDataSource;
import com.ccp.dev.system.service.SysDataSourceService;
import net.sf.json.JSONObject;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * SYS_DATA_SOURCE 控制器类
 *
 * @author zhaowj
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/dataSource")
public class SysDataSourceController extends SysBaseController {

    @Resource
    private SysDataSourceService sysDataSourceService;

    /**
     * 数据列表页面跳转
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/list")
    public String dataSource() {
        return "dataSource/list";
    }

    /**
     * 页面跳转添加页面
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/add")
    public String addSource() {
        return "dataSource/add";
    }

    /**
     * 页面跳转编辑页面
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/edit")
    public String editSource(HttpServletRequest request , Model model){
        String dataSourceId = RequestUtil.getString(request,"dataSourceId");
        model.addAttribute("dataSourceId",dataSourceId);
        return "dataSource/edit";
    }


    /**
     * 页面跳转导入页面
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    public String importXml() {
        return "dataSource/import";
    }

    /**
     * 添加或更新SYS_DATA_SOURCE
     *
     * @param sysDataSource 数据源对象
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @ResponseBody
    public ResultData save(@RequestBody SysDataSource sysDataSource) {
        SysDataSource sysDataSourceAlias = sysDataSourceService.getByAliasAndId(sysDataSource.getAlias(),sysDataSource.getId());
        if (sysDataSourceAlias != null) {
            return getResultDataError("dataSource.save.aliasWarning");
        }
        int count = sysDataSourceService.addOrUpdate(sysDataSource);
        if (count > 0) {
            // 加入系统数据源
            if (sysDataSource.getEnabled()) {
                try {
                    DataSourceUtil.addDataSource(sysDataSource.getAlias(), sysDataSourceService.getDsFromSysSource(sysDataSource));
                } catch (Exception e) {
                    e.printStackTrace();
                    return getResultDataError("save.failure");
                }
            }
            return getResultDataSuccess("save.success");
        } else {
            return getResultDataError("save.failure");
        }
    }

    /**
     * 取得SYS_DATA_SOURCE分页列表
     *
     * @param request 请求
     */
    @ResponseBody
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    public ResultData list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        List<SysDataSource> list = sysDataSourceService.queryList(queryFilter);
        return getResultDataSuccess("operation.success",queryFilter.getPageBean().getTotalCount(),list);
    }

    /**
     * 取得SYS_DATA_SOURCE列表
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public ResultData listAll() {
        List<SysDataSource> list = sysDataSourceService.queryListALL();
        return getResultDataSuccess("operation.success",list);
    }

    /**
     * 导出系统数据源xml。
     *
     * @param request  请求
     * @param response 响应
     * @throws Exception 异常
     */
    @RequestMapping("/exportXml")
    public void exportXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String strXml = "";
        String fileName;
        String[] tableIds = RequestUtil.getStringAryByStr(request, "tableIds");
        if (BeanUtils.isEmpty(tableIds)) {
            List<SysDataSource> list = sysDataSourceService.queryListALL();
            if (BeanUtils.isNotEmpty(list)) {
                strXml = sysDataSourceService.exportXml(list);
                fileName = SystemConst.STR_ALL_DATASOURCE + DateFormatUtil.getNowByString("yyyyMMddHHmm") + ".xml";
            } else {
                //数据源为空，文件名默认为export.xml
                fileName = "export.xml";
            }
        } else {
            strXml = sysDataSourceService.exportXml(tableIds);
            fileName = DateFormatUtil.getNowByString("yyyyMMddHHmm") + ".xml";
            if (tableIds.length == 1) {
                SysDataSource sysDataSource = sysDataSourceService.getOneById(tableIds[0]);
                fileName = sysDataSource.getName() + "_" + fileName;
            } else {
                fileName = SystemConst.STR_DATASOURCE + fileName;
            }
        }
        FileUtil.downLoad(request, response, strXml, fileName);
    }

    /**
     * 导入系统数据源的XML
     *
     * @param request 请求
     */
    @RequestMapping("/importXml")
//    @ResponseBody
    public void importXml(MultipartHttpServletRequest request,HttpServletResponse response) throws Exception {
        PrintWriter writer = response.getWriter();
        MultipartFile fileLoad = request.getFile("file");
        String filename = fileLoad.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        if (!(StringPool.XML).equals(prefix)) {
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("dataSource.importXml.fileTypeWarn"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        } else {
            try {
                sysDataSourceService.importXml(fileLoad.getInputStream());
                SysAuditThreadLocalHolder.putParamerter("success", true);
                JSONObject json = JSONObject.fromObject(getResultDataSuccess("dataSource.importXml.success"));
                writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
            } catch (Exception e) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
                writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
            }
        }
    }

    /**
     * 删除SYS_DATA_SOURCE
     *
     * @param id 数据源id
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    public ResultData del(@RequestParam("id") String id) {
        int i = sysDataSourceService.delSysDataSourceById(id);
        if (i > 0) {
            return getResultDataSuccess("delete.success");
        } else {
            return getResultDataError("delete.failure");
        }
    }


    /**
     * 获取某个数据源信息
     *
     * @param id 数据源id
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET + "SysDataSource")
    @ResponseBody
    public ResultData getSysDataSource(@RequestParam("id") String id) {
        SysDataSource sysDataSource = sysDataSourceService.getOneById(id);
        if (BeanUtils.isNotEmpty(sysDataSource)) {
            return getResultDataSuccess("operation.failure",sysDataSource);
        } else {
            return getResultDataError("operation.failure");
        }
    }


    /**
     * 测试连接
     *
     * @param sysDataSource 数据源对象
     * @return ResultData对象
     */
    @RequestMapping("/checkConnection")
    @ResponseBody
    public ResultData checkConnection(@RequestBody SysDataSource sysDataSource) {
        boolean checkConnection;
        try {
            sysDataSource.setSettingJson(StringEscapeUtils.unescapeHtml4(sysDataSource.getSettingJson()));
            checkConnection = sysDataSourceService.checkConnection(sysDataSource);
        } catch (Exception e) {
            checkConnection = false;
        }
        if (checkConnection) {
            return getResultDataSuccess("dataSource.connection.success");
        } else {
            return getResultDataError("dataSource.connection.failure");
        }
    }
}
